<template>
  <DataTable url="user/list" pageable  ref="ds">
    <template #tools="table">
      <Button v-if="ADD" icon="jeicon-add" color="primary" @click="add">新增</Button>
      <Button v-if="EDIT" :disabled="selects.length!=1" icon="h-icon-edit" text-color="primary" @click="editFirst">修改</Button>
      <Button v-if="EDIT" :disabled="selects.length!=1" icon="h-icon-edit" text-color="primary" @click="alterPswd">修改密码</Button>
      <Poptip v-if="DELETE" :disabled="selects.length==0" class="h-btn" content="确定删除所选记录？"
              @confirm="del">
        <Button icon="h-icon-trash"  text-color="red" :disabled="selects.length==0">删除</Button>
      </Poptip>
    </template>
    <template #search="table">
      <Select v-model="table.params.enable" :datas="{1:'启用',0:'禁用'}" placeholder="状态" @change="table.reload()" style="width:80px"></Select>
      <Input type="text" v-model="table.params.username" placeholder="用户名"/>
      <Input type="text" v-model="table.params.name" placeholder="姓名"/>
<!--      <CategoryPicker-->
<!--          v-model="table.params.branchSn"-->
<!--          :option="branchOpts"-->
<!--          style="width:250px;display:inline-block;"-->
<!--          placeholder="组织机构"-->
<!--      />-->
    </template>
    <template #default="table">
      <div style="height: 100%;overflow: hidden">
        <div style="display: flex;justify-content: space-between;height: 100%;overflow: hidden;">
          <div style="width: 200px;height: 100%;border: 1px solid #eeeeee;border-right:none;padding:5px;overflow-y:auto; ">
            <Tree class="scroll"
                ref="demoRef"
                :option="branchOpts"
                v-model="table.params.branchSn"
                @change="table.reload()"
                filterable="true"
                :toggleOnSelect="false"
            />
          </div>
          <div style="height: 100%;flex:1">
            <Table :datas="table.data" :loading="table.loading" @trDblClick="edit" @select="selected" checkbox selectWhenClickTr>
              <TableItem title="序号" prop="$serial" :width="50"></TableItem>
              <TableItem title="用户名" prop="username"></TableItem>
              <TableItem title="姓名" prop="name"></TableItem>
              <TableItem title="机构" prop="branchName" ></TableItem>
              <TableItem title="角色" prop="role" ></TableItem>
              <TableItem title="手机号" prop="phone" :width="120"></TableItem>
              <TableItem title="性别" prop="gender" dict="Gender" :width="50"></TableItem>
              <TableItem title="状态" :width="100">
                <template #default="{data}">
                  <HSwitch v-model="data.enable" @change="switchStatus(data)">
                    <template v-slot:open>启用</template>
                    <template v-slot:close>禁用</template>
                  </HSwitch>
                </template>
              </TableItem>
            </Table>
          </div>
        </div>

      </div>
    </template>
  </DataTable>
    <UserDialog ref="dlg" :branchOptions="branchOpts" @change="reload">
    </UserDialog>
    <Prompt title="请输入新密码" type="password" ref="passwordDlg"/>
<!--  </div>-->
</template>
<script setup>
import {ajax, util, hasPermission, default as f} from 'framework'
import UserDialog from './userDialog.vue'
import {ref, reactive, onMounted} from 'vue'
import {message} from 'heyui'
import DataTable from "../coms/DataTable.vue";
//import Prompt from "../coms/Prompt.js";
// let r=Vue.withAsyncContext(()=>ajax.get('system/dict?type=gender'))
// console.log(r)
// let table = ajax.createDs('user/list', true)
const demoRef = ref(null);


function unfold() {
  if (demoRef.value) {
    demoRef.value.expandAll();
  }
}

const ADD = hasPermission('platform.user.add'), EDIT = hasPermission('platform.user.edit'),
    DELETE = hasPermission('platform.user.delete')
const selects = ref([]), dlg = ref(null), passwordDlg = ref(null)//,branches=ref([])
const ds=ref(null)
const branchOpts = reactive({
  keyName: 'sn',
  titleName: 'fullName',
  dataMode: 'tree',
  datas: f.getBranches('tree')
})
f.getBranches('mapper').onload(function(){
  setTimeout(unfold)
})
//const formatBranch = f.getBranches('mapper')
//let branchMap={}
onMounted(() => {
  //branches.value=getBranches('tree')
  // branchOpts.datas=getBranches('tree')
  // ajax.get("branch/list").then(r => {
  //   // branchOption.datas = r.data;
  //    branches.value=r.data
  //   // branchMap=util.asMap(r.data,it=>it.sn)
  //    branchOpts.datas=util.asTree(r.data,"id","pid")
  //    table.load()
  //  })

 // formatBranch.onload(() => ds.value.load())
})
// function formatBranch(v){
//   let branch=branchMap[v]
//   return branch?branchMap[v].fullName:v
// }


function reload() {
  selects.value = []
  ds.value.load()
}

// function search() {
//   selects.value = []
//   table.pagination.page = 1;
//   table.load()
// }

function selected(v) {
  selects.value = v.map(it => util.fields(it, 'username,id'))
}

function add() {
  dlg.value.show()
}

function editFirst() {
  if (selects.value.length == 0) {
    return;
  }
  edit(selects.value[0])
}

function edit(v) {
  if (!EDIT) {
    return;
  }
  dlg.value.show(util.fields(v, 'username,id'))
}

function del() {
  ajax.post('user/delete', selects.value).then(r => {
    reload()
  })
}

//修改密码
function alterPswd() {
  if (selects.value.length == 0) {
    return;
  }
  let user = selects.value[0];
  passwordDlg.value.show().then(r => {
    ajax.formPost("user/alterPassword", {username: user.username, password: r}).then(r => {
      message("已修改")
      reload()
    }).catch(e => {
      message({type: 'error', text: '修改失败'})
    })
  })
  // HeyUI.prompt('请输入新密码').then(r=>{
  //
  // })
}

//切换用户状态
function switchStatus(user) {
  //console.log(user.enable)
  ajax.post("user/switchStatus", {username: user.username, enable: user.enable}).then(r => {
    message("状态已切换")
    reload()
  }).catch(e => {
    message({type: 'error', text: '切换失败'})
  })
}


</script>
